package great.easychat.help.update;

import android.annotation.SuppressLint;
import android.content.Context;

import java.io.File;

import great.easychat.help.util.ToastUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class UpdateDownloader {

    private Context context;
    private boolean isFileOk = false;

    public UpdateDownloader(Context context) {
        this.context = context;
    }

    private String getFileApkPath(String versionCode) {
        return FileConstants.DIR_DOWNLOAD + versionCode + "update.apk";
    }

    /**
     * 下载器绑定进度回调
     */
    public void attachDialogCallBack(String versionCode, String url, String fileProviderName, IupdateDialogCallBack updateDialogCallBack) {
        startDownLoad(versionCode, url, fileProviderName, updateDialogCallBack);
    }


    @SuppressLint("CheckResult")
    private void startDownLoad(String versionCode, String url, String fileProviderName, IupdateDialogCallBack updateDialogCallBack) {
        File file = new File(getFileApkPath(versionCode));
        if (file.exists() && isFileOk) {
            install(file, fileProviderName);
            return;
        }
//        Toast.makeText(context, "开始下载", Toast.LENGTH_SHORT).show();
        new DownloadRequest(url, getFileApkPath(versionCode))
                .download()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(it -> {
                    updateDialogCallBack.onUpdateProgress(it.first, it.second);
                    if (it.first >= it.second) {
                        ToastUtil.show("下载完成");
                        updateDialogCallBack.onComplete(true);
                        if (checkFile(file)) {
                            isFileOk = true;
                            //文件已经存在　下载成功　安装失败　可能是取消安装了
                            install(file, fileProviderName);
                        }
                    }
                }, error -> {
                    isFileOk = false;
                    ToastUtil.show("更新失败");
                    updateDialogCallBack.onComplete(false);
                    deleteOldFile(file);
                });
    }


    private void deleteOldFile(File file) {
        if (file.exists()) {
            file.delete();
        }
    }

    private boolean checkFile(File file) {
        return file.exists();
    }

    private void install(File fileApk, String fileProviderName) {
        ApkInstallUtils.installApk(context, fileApk, fileProviderName);
    }
}
